package com.lanou3g.hw0416;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 18/4/16.
 */
public class IOUtis {

    public static final String FILE_NAME = "user.txt";  //psvs 字符串常量简写
    /*
    * 存储用户信息
    * @param user 要存储的用户信息
    *
    * */

    public static void saveUser(User user) {
        File file = new File(FILE_NAME);
        FileOutputStream os = null;     //使用FileOutputStream的父类创建
        OutputStreamWriter osw = null;
        PrintWriter pw = null;

        try {
            if (!file.exists()) {      // 将if判断放到try - catch里面
                file.createNewFile();
            }
            pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
            String userInfo = user.getUsername() + ":" + user.getPwd();
            //一条信息是一行
            pw.println(userInfo);   //写流
            pw.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(pw);
        }


    }


    // 取用户
    public static ArrayList<User> initUsers(){

        ArrayList<User> users = new ArrayList<>();
        File file = new File(FILE_NAME);
        if (!file.exists()){  //文件不存在,说明一个用户都没存
            return users;  //返回空
        }

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

            String line = "";

            while ((line = reader.readLine()) != null){
                String[] info = line.split(":");
                User user = new User();
                if(info.length == 2){
                    user.setUsername(info[0]);
                    user.setPwd(info[1]);
                    users.add(user);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeAll(reader);
        }

        return users;

    }




    //判断 是否存在已有账户
    public static Boolean noSameusername(List<User> users,String username){
        Boolean isSame = false;
        if (users == null){
            return null;
        }
        for (User user : users) {
            if (username.equals(user.getUsername())){
                isSame = true;
                break;
            }
        }
        return isSame;
    }

    // 封装关闭流的方法 ,有几个流需要关,就传几个参数,提高代码的整洁度
    public static void closeAll(Closeable... closeables) {  //Closeable 是有close方法的实现类

        if (closeables == null) {  //判断数组是否为空
            return;
        }

        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
